import { message } from 'antd';
import { list, create, edit, dele } from '../services/role';
import tools from '../../../utils';

export default {
  namespace: 'role',

  state: {
    data: [],
    success: true,
    names: [], // 存放所有的名称, 用于检测是否重名, 防止重复添加
    treeData: [], // 可用功能树形数据
  },

  effects: {
    *list({ payload }, { call, put }) {
      const response = yield call(list, payload);
      yield put({ type: 'callbackList', response });
    },
    *create({ payload }, { call, put }) {
      const response = yield call(create, payload);
      yield put({ type: 'callbackSave', response });
    },
    *edit({ payload }, { call, put }) {
      const response = yield call(edit, payload);
      yield put({ type: 'callbackSave', response });
    },
    *dele({ payload }, { call, put }) {
      const response = yield call(dele, payload);
      yield put({ type: 'callbackSave', response });
    },
  },

  reducers: {
    callbackList(st, { response }) {
      const state = st;
      const { success = true, data = [], resData = [] } = response;
      let { menuData = [] } = response;

      if (!success) return { ...state };

      state.data = data;
      state.names = [];
      data.map(({ name }) => { state.names.push(name) });

      if (!menuData || !resData) return { ...state };

      if (!menuData.length || !resData.length) return { ...state };

      menuData = menuData.map(({ id, pid, name, page }) => ({
        pid,
        key: id,
        title: name,
        page,
        selectable: false,
      }));

      state.treeData = tools.funcPidToChildren(menuData, 'key').map(item => {
        const { page } = item;
        let { children } = item;

        if (!children) return item;
        if (!children.length) return item;

        children = children.map(itemChild => {
          const pagePath = page + '/' + itemChild.page + '/';

          resData.map(({ resUrl, name }) => {
            if (resUrl.indexOf(pagePath) !== 0) return;

            if (!itemChild.children) itemChild.children = [];
            itemChild.children.push({
              key: resUrl,
              title: name,
              selectable: false,
            });
          });

          return itemChild;
        });

        return { ...item, children };
      });
      return { ...state };
    },
    callbackSave(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) message.success(response.msg);
      return { ...state };
    },
  },
};
